package com.example.demorabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ队列配置
 *
 * @author wangbin
 */
@Configuration
public class RabbitConfig {
    public static final String TEST_QUEUE_NAME_1 = "testQueue1";
    public static final String TEST_QUEUE_NAME_2 = "testQueue2";

    /**
     * 死信队列key
     */
    public static final String DEAD_LETTER = "testDeadLetter";
    /**
     * 测试队列数组
     */
    public static final String[] QUEUE_LIST = new String[]{TEST_QUEUE_NAME_1, TEST_QUEUE_NAME_2};

    @Bean
    CommandLineRunner commandLineRunner(ConfigurableApplicationContext applicationContext) {
        return args -> {
            ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();

            DirectExchange deadLetterExchange = new DirectExchange(DEAD_LETTER + ".exchange");
            Queue dealLetterQueue = QueueBuilder.durable(DEAD_LETTER + ".queue").build();
            Binding dealLetterBinding = BindingBuilder.bind(dealLetterQueue).to(deadLetterExchange).with(DEAD_LETTER);

            beanFactory.registerSingleton("deadLetterExchange", deadLetterExchange);
            beanFactory.registerSingleton("dealLetterQueue", dealLetterQueue);
            beanFactory.registerSingleton("dealLetterBinding", dealLetterBinding);

            for (String q : QUEUE_LIST) {
                DirectExchange directExchange = new DirectExchange(q + ".exchange");
                Queue queue = QueueBuilder.durable(q + ".queue")
                        .withArgument("x-dead-letter-exchange", DEAD_LETTER + ".exchange")
                        .withArgument("x-dead-letter-routing-key", DEAD_LETTER).build();
                Binding binding = BindingBuilder.bind(queue).to(directExchange).with(q);

                beanFactory.registerSingleton(q + "Exchange", directExchange);
                beanFactory.registerSingleton(q + "Queue", queue);
                beanFactory.registerSingleton(q + "Binding", binding);
            }
        };
    }
}
